//
//  ProjectDetailViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 16/1/13.
//  Copyright © 2016年 李萍. All rights reserved.
//

import UIKit
import Foundation
import Alamofire
import SwiftyJSON

class ProjectDetailViewController: UITableViewController {
    var private_token: String!
    var nameSpace : String!
    var cell : ProjectDetailCell!
    var detailProject : GTProject!
    var projectID: Int!
    var detailProjectUrl: String!
    
    init(projectID: Int, namespace: String) {
        self.projectID = projectID
        self.nameSpace = namespace
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "ProjectDetailCell", bundle: nil), forCellReuseIdentifier: "projectDetailCell")
        cell = self.tableView.dequeueReusableCellWithIdentifier("projectDetailCell") as! ProjectDetailCell
        
        self.tableView.backgroundColor = UIColor.init(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
        self.tableView.tableFooterView = UIView.init(frame: CGRectZero)
        
        self.fetchForProjectDetail()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "projectDetails_more"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ProjectDetailViewController.leftButtonClick));
    }
    
    func leftButtonClick() {
        
        let bottomAction = UIAlertController.init(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        bottomAction.addAction(UIAlertAction.init(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
        bottomAction.addAction(UIAlertAction.init(title: "分享项目", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
            print("分享")
        }))
        bottomAction.addAction(UIAlertAction.init(title: "复制链接", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
            print("复制链接 \(self.detailProjectUrl)")
            
            UIPasteboard.generalPasteboard().string = self.detailProjectUrl
            
            print("复制后的内容＝\(JSON(UIPasteboard.generalPasteboard().string!))")
            
        }))
        bottomAction.addAction(UIAlertAction.init(title: "在浏览器中打开", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
            UIApplication.sharedApplication().openURL(NSURL.init(string: self.detailProjectUrl)!)
        }))
        
        self.presentViewController(bottomAction, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //实现列表
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier("projectDetailCell", forIndexPath: indexPath) as! ProjectDetailCell
            if  self.detailProject != nil {
                cell.setContentForDetailProject(self.detailProject)
                cell.watchButton.addTarget(self, action: #selector(ProjectDetailViewController.touchWatchButton), forControlEvents: UIControlEvents.TouchUpInside)
                cell.starButton.addTarget(self, action: #selector(ProjectDetailViewController.touchStarButton), forControlEvents: UIControlEvents.TouchUpInside)
            }
            
            return cell
        } else {
            let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            
            if  self.detailProject != nil {
                let userName = JSON((self.detailProject.owner?.name)!)
                cell.textLabel!.text = ["拥有者 \(userName)", "Readme", "代码", "问题", "提交"][indexPath.row]
                cell.imageView?.image = UIImage(named: ["projectDetails_owner", "projectDetails_readme", "projectDetails_code", "projectDetails_issue", "projectDetails_branch"][indexPath.row])
            }
            
            
            return cell
        }
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else {
            return 5
        }
    }
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if detailProject != nil {
                cell.contentLabel.text = detailProject.projectDescription
                let height = cell.contentLabel.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
                return height + 220
            }
            return 220
        } else {
            return 40
        }
    }
    
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 215
        } else {
            return 0
        }
    }
    
    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        }
        return 20
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.section == 1 {
            switch indexPath.row {
            case 0 :
                let titleView = TitleViewController(titles: ["动态", "项目", "Star", "Watch"],
                    controllers: [EventsViewController(userID: (detailProject.owner?.userID)!),
                        ProjectsTableViewController(userID: (detailProject.owner?.userID)!, projectType: 9),
                        ProjectsTableViewController(userID: (detailProject.owner?.userID)!, projectType: 5),
                        ProjectsTableViewController(userID: (detailProject.owner?.userID)!, projectType: 6)],
                    hasNav: true,
                    hasTabbar: false,
                    titlesHeight: CGFloat(35),
                    buttonWidth: 0,
                    footHeight: CGFloat(3))
                
                titleView.automaticallyAdjustsScrollViewInsets = false
                titleView.buttonBackgroundColor = UIColor.grayColor()
                titleView.buttonSelectedColor = UIColor.blackColor()
                titleView.buttonUnSelectedColor = UIColor.whiteColor()
                
                self.navigationController?.pushViewController(titleView, animated: true)
            case 1 :
                let readMeView = ReadMeViewController()
                readMeView.title = self.detailProject.name
                readMeView.nameSpace = self.detailProject.nameSpace!
                self.navigationController?.pushViewController(readMeView, animated: true)
            case 2 :
                let filesView = FilesViewController()
                filesView.currentPath  = ""
                filesView.title = self.detailProject.name
                filesView.nameSpace = self.detailProject.nameSpace!
                self.navigationController?.pushViewController(filesView, animated: true)
            case 3 :
                let issuesView = IssueViewController()
                issuesView.nameSpace = self.detailProject.nameSpace!
                issuesView.title = self.detailProject.name
                self.navigationController?.pushViewController(issuesView, animated: true)
            case 4 :
                let commitView = CommitsViewController()
                commitView.nameSpace = self.detailProject.nameSpace
                commitView.page = 1
                commitView.refName = "master"
                commitView.projectID = self.detailProject.projectID
                self.navigationController?.pushViewController(commitView, animated: true)
            default :
                break
            }
        }
    }
    
    //点击按钮是否watch
    func touchWatchButton() -> Void {
        print("watch")
        let userinfos = UserInfos()
        let private_token = userinfos.getprivateToken()
        
        let watchStr = (self.detailProject.wacthed == true) ? "unwatch" : "watch"
        
        let strUrl: String!
        if private_token.isEmpty {
            strUrl = "https://git.oschina.net/api/v3/projects/"+self.nameSpace+"/\(watchStr)"
        } else {
            strUrl = "https://git.oschina.net/api/v3/projects/"+self.nameSpace+"/\(watchStr)"+"?private_token=\(private_token)"
        }
        Alamofire.Manager.sharedInstance.request(Method.POST, strUrl).responseJSON { Response in
            if let results = Response.result.value {
                let watchCount = JSON(results)["count"].intValue
                
                print(watchCount)
                
                self.detailProject.wacthed = (self.detailProject.wacthed == true) ? false : true
                self.detailProject.watchesCount = watchCount
                self.tableView.reloadData()
            }
        }
    }
    
    //点击是否star
    func touchStarButton() -> Void {
        print("star")
        let userinfos = UserInfos()
        let private_token = userinfos.getprivateToken()
        
        let starStr = (self.detailProject.stared == true) ? "unstar" : "star"
        
        let strUrl: String!
        if private_token.isEmpty {
            strUrl = "https://git.oschina.net/api/v3/projects/"+self.nameSpace+"/\(starStr)"
        } else {
            strUrl = "https://git.oschina.net/api/v3/projects/"+self.nameSpace+"/\(starStr)"+"?private_token=\(private_token)"
        }
        Alamofire.Manager.sharedInstance.request(Method.POST, strUrl).responseJSON { Response in
            if let results = Response.result.value {
                
                let starCount = JSON(results)["count"].intValue
                
                print(starCount)
                self.detailProject.stared = (self.detailProject.stared == true) ? false : true
                self.detailProject.starsCount = starCount
                self.tableView.reloadData()
            }
        }
    }
    
    //获取数据
    func fetchForProjectDetail() -> Void {
        let userinfos = UserInfos()
        let private_token = userinfos.getprivateToken()
        
        let strUrl: String!
        if private_token.isEmpty {
            strUrl = "https://git.oschina.net/api/v3/projects/"+self.nameSpace
        } else {
            strUrl = "https://git.oschina.net/api/v3/projects/"+self.nameSpace+"?private_token=\(private_token)"
        }
        
        self.detailProjectUrl = "https://git.oschina.net/"+self.nameSpace
        
        self.detailProjectUrl = self.detailProjectUrl.stringByReplacingOccurrencesOfString("%2F", withString: "/")
        
        Alamofire.Manager.sharedInstance.request(Method.GET, strUrl).responseJSON { Response in
            if let results = Response.result.value {
                self.detailProject = GTProject(json: JSON(results))
                self.tableView.reloadData()
            }
        }
        
    }
}
